package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.lindi.enums.LindiIndexEnum;
import com.minimalist.common.entity.lindi.enums.TownEnum;
import com.minimalist.common.entity.lindi.po.LindiIndex;
import com.minimalist.common.entity.lindi.vo.index.LindiIndexQueryVO;
import com.minimalist.common.entity.lindi.vo.index.LindiIndexVO;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.manager.LindiIndexManager;
import com.minimalist.lindi.mapper.LindiIndexMapper;
import com.minimalist.lindi.service.LindiIndexService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 林地指标表 服务层实现。
 *
 * @author 11987
 * @since 2025-04-16
 */
@Service
public class LindiIndexServiceImpl extends ServiceImpl<LindiIndexMapper, LindiIndex>
        implements LindiIndexService{
    private static final Logger log = LoggerFactory.getLogger(LindiIndexServiceImpl.class);


    @Autowired
    private LindiIndexMapper mapper;

    @Autowired
    private LindiIndexManager lindiIndexManager;

    @Override
    public void addIndex(LindiIndexVO indexVO){
        LindiIndex lindiIndex = BeanUtil.copyProperties(indexVO, LindiIndex.class);
        lindiIndex.setIndexId(UnqIdUtil.uniqueId());
        int insert = mapper.insert(lindiIndex, true);
        Assert.isTrue(insert == 1, () -> new BusinessException(
                LindiIndexEnum.ErrorMsgEnum.ADD_INDEX_ERROR.getDesc()));
    }

    @Override
    public void deleteIndexByIndexId(Long indexId){
        LindiIndex lindiIndex = mapper.selectIndexByIndexId(indexId);
        Assert.notNull(lindiIndex, () -> new BusinessException(LindiIndexEnum.ErrorMsgEnum
                .NONENTITY_INDEX.getDesc()));
        int delete = mapper.delete(lindiIndex);
        Assert.isTrue(delete == 1, () -> new BusinessException(
                LindiIndexEnum.ErrorMsgEnum.DELETE_INDEX_ERROR.getDesc()));
    }

    @Override
    public void updateIndexByIndexId(LindiIndexVO indexVO){
        LindiIndex lindiIndex = mapper.selectIndexByIndexId(indexVO.getIndexId());
        Assert.notNull(lindiIndex, () -> new BusinessException(LindiIndexEnum.ErrorMsgEnum
                .NONENTITY_INDEX.getDesc()));
        BeanUtil.copyProperties(indexVO, lindiIndex
                , CopyOptions.create().ignoreNullValue());
        int update = mapper.update(lindiIndex);
        Assert.isTrue(update == 1, () -> new BusinessException(
                LindiIndexEnum.ErrorMsgEnum.UPDATE_INDEX_ERROR.getDesc()));
    }

    @Override
    public PageResp<LindiIndexVO> getPageIndexList(LindiIndexQueryVO queryVO){
//        //分页查询
//        Page<LindiIndex> indexPage = mapper.selectPageIndexList(queryVO);
//        //数据转换
//        List<LindiIndexVO> indexVOList = BeanUtil.copyToList(indexPage.getRecords()
//                , LindiIndexVO.class);
//        return new PageResp<>(indexVOList, indexPage.getTotalRow());
        return lindiIndexManager.getLindiIndex(queryVO);
    }

    @Override
    public LindiIndexVO getIndexByIndexId(Long indexId){
        LindiIndex lindiIndex = mapper.selectIndexByIndexId(indexId);
        Assert.notNull(lindiIndex, () -> new BusinessException(LindiIndexEnum.ErrorMsgEnum
                .NONENTITY_INDEX.getDesc()));
        return BeanUtil.copyProperties(lindiIndex, LindiIndexVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initTownIndex(){
        long count = mapper.selectCountByQuery(QueryWrapper.create());
        if (count == 0){
            log.info("开始初始化镇街指标数据");
            //根据镇街枚举值初始化指标
            List<LindiIndex> indexList = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();

            // 遍历所有镇街枚举值
            for (TownEnum town : TownEnum.values()){
                LindiIndex lindiIndex = new LindiIndex();
                lindiIndex.setIndexId(UnqIdUtil.uniqueId());
                lindiIndex.setLocationName(town.getDesc());
                // 设置初始指标值，这里设置为100
                lindiIndex.setPurchaseIndex("100");
                lindiIndex.setTradeIndex("0");
                lindiIndex.setCreateId(0L);
                lindiIndex.setCreateTime(now);
                lindiIndex.setUpdateId(0L);
                lindiIndex.setUpdateTime(now);
                indexList.add(lindiIndex);
            }

            // 批量插入数据
            if (!indexList.isEmpty()){
                mapper.insertBatch(indexList);
                log.info("成功初始化{}条镇街指标数据", indexList.size());
            }
        } else{
            log.info("镇街指标数据已存在，无需初始化");
        }
    }

    @Override
    public Map<String, Object> getStatistics(){
        Map<String, BigDecimal> statistics = lindiIndexManager.getReserveStatistics();
        Map<String, Object> result = new HashMap<>();
        result.putAll(statistics);
        return result;
    }

    @Override
    public List<String> getEnableTradeTownNameList(){
        return lindiIndexManager.getEnableTradeTownNameList();
    }
}

